package com.mrd.gtimp.base.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.gtimp.base.entity.Module;
import com.mrd.gtimp.base.repository.ModuleDao;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author qiul
 */
@Service
public class ModuleBiz extends BaseBiz<Module> {
    @Resource
    private ModuleDao moduleDao;

    /**
     * 通过用户账号使用sql的方式查询模块权限集合(解决部分代码位置无法获取到hibernate session的问题)
     *
     * @param account 账号
     * @return 模块权限集合，账号为空时返回一个空集合
     */
    public List<Module> findModuleBySqlUseAccount(String account) {
        List<Module> modules = new ArrayList<>();
        if (StringUtils.isEmpty(account)) {
            return modules;
        }
        String sql = "select distinct t.id,t.module_name,t.link,t.pid,t.m_order from t_sys_module t join t_sys_role_m_module rm on t.id = rm.moduleid join t_sys_role r on r.id = rm.roleid join t_sys_role_user ru   on r.id = ru.role_id join t_sys_user u   on ru.user_id = u.u_id  where u.u_account = :account and r.r_state = '0' and t.m_state = '0' order by t.m_order,t.module_name";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("account", account);
        try {
            List<Object> objects = baseRepository.findEntityBySql(sql, 0, 1000, parameters);
            for (Object object : objects) {
                Object[] o = (Object[]) object;
                Module module = new Module();
                module.setId((String) o[0]);
                module.setName((String) o[1]);
                module.setLink((String) o[2]);
                if (StringUtils.isNotEmpty((String) o[3])) {
                    Module parent = new Module();
                    parent.setId((String) o[3]);
                    module.setParent(parent);
                }
                module.setOrder(((BigDecimal) o[4]).intValue());
                modules.add(module);
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return modules;
    }

    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("moduleDao")
    public void setBaseRepository(BaseRepository<Module, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

}
